package com.cx.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 
/**
 * 读取DataSource01数据源<br>
 */
// DataSource01
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.cx", sqlSessionFactoryRef = "chainJKTSqlSessionFactory")
public class ChainJKTDataSourceConfig {
 
	/**
	 * @methodDesc: 功能描述:(配置test01数据库)
	 */
	@Bean(name = "chainJKTDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.chainjkt")
	public DataSource testDataSource() {
		return DataSourceBuilder.create().build();
	}
 
	/**
	 * @methodDesc: 功能描述:(test1 sql会话工厂)
	 */
	@Bean(name = "chainJKTSqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("chainJKTDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*/*.xml"));
		bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis/mybatis-config.xml"));
		return bean.getObject();
	}
 
	/**
	 * @methodDesc: 功能描述:(test1 事物管理)
	 */
	@Bean(name = "chainJKTTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("chainJKTDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
 
	@Bean(name = "chainJKTSqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier("chainJKTSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
 
}
